<?php

namespace App\Services\Api;

use App\Models\User;
use App\Models\UserSubscribe;
use App\Models\UserIntegralUsable;
use App\Models\UserIntegralChangeRecord;
use App\Models\UserVipInfo;
use App\Models\UserVipUseRecord;
use App\Services\Admin\UserSubscribeService;
use Illuminate\Support\Facades\DB;
use App\Models\UserCoupon;
use App\Models\UserCouponRecord;

class SubscribeServices
{

    public function create_subscribe($model, $data)
    {

    }

    /**
     * @param $request
     * @param $subscribeModel \App\Models\UserSubscribe
     */
    public function my_subscribe($request, $user_id, $subscribeModel)
    {
        $query = $subscribeModel->WhereUserID($user_id);
        if (!empty($request->subscribe_status) && $request->subscribe_status != 5) {
            $query->where('subscribe_status', $request->subscribe_status);
        } elseif ($request->subscribe_status == 5) {
            $query->whereIn('subscribe_status', [5, 6, 7]);
        }

        $data = $query
            ->with([
                'class_base' => function ($q) {
                    $q->select([
                        'id',
                        'class_cove',
                    ]);
                },
                'class_base_info',
                'user_vip_use_record' => function ($q){
                    $q->select('user_vip_name','id');
                }
            ])
            ->OrderCreatedAt('desc')
            ->get()
            ->toArray();
        if (!empty($data)) {

            foreach ($data as $k => $v) {
                $base_info_ids[] = $v['class_base_info_id'];
                $class_subscribe_number = (new UserSubscribe)->ClassSubscribeNumber($base_info_ids, $v['class_time'], $v['end_time']);

                if ($class_subscribe_number >= $v['class_base_info']['class_number_people']) {
                    $data[$k]['full_status'] = 1;
                } else {
                    $data[$k]['full_status'] = 2;
                }

                /*            if($v['subscribe_status'] == 1){
                                //排位
                                $queue_array = $subscribeModel
                                    ->select(['id','user_id'])
                                    ->where('class_base_info_id',$v['class_base_info_id'])
                                    ->where('subscribe_status',1)
                                    ->where('class_time',$v['class_time'])
                                    ->where('end_time',$v['end_time'])
                                    ->orderBy('created_at','asc')
                                    ->get();
                            }*/

            }

        }

        return $data;
    }

    /**
     * @param $request
     * @param $user_id
     * @param $subscribeModel \App\Models\UserSubscribe
     */
    public function change_subscribe($request, $subscribeModel)
    {
        DB::beginTransaction();

        $subscribeObj = $subscribeModel->WhereID($request->subscribe_id)->first();

        if($subscribeObj->subscribe_status == 1){
            //排队中
            $msg_title = '取消候補';
        }elseif($subscribeObj->subscribe_status == 2){
            //预约成功
            $msg_title = '取消預約';
        }

        if($subscribeObj->user_id != auth()->user('api')->id)throw new \Exception('非法操作!');

        if($subscribeObj->subscribe_status == 4)throw new \Exception('已操作過了!');


        $msg_time_day = date("Y-m-d", strtotime("{$subscribeObj->class_time}"));

        $start_class_time_array = date("H:i", strtotime("{$subscribeObj->class_time}"));

        $end_class_time_array = date("H:i", strtotime("{$subscribeObj->end_time}"));

        $msg_class_time_string = "{$start_class_time_array}-{$end_class_time_array}";

        //先把排队顶上
        if ($subscribeObj->subscribe_status == 2) UserSubscribeService::change_all_ranks($subscribeObj);

        $subscribeObj->subscribe_status = 4;

        $subscribeObj->save();

        if(!empty($subscribeObj->user_vip_use_record_id)){

            //查詢記錄
            $user_vip_record = (new UserVipUseRecord())->where('id', $subscribeObj->user_vip_use_record_id)->first();

            $msg_result = [
                $msg_title,
                "{$user_vip_record->user_vip_name} 會員卡退還使用次數",
                $msg_time_day,
                $msg_class_time_string,
                $subscribeObj->class_name
            ];

            //扣减积分
            $remark = implode("/", $msg_result);

            UserSubscribeService::cancel_return_vip($subscribeObj, $remark, $user_vip_record, auth()->user('api')->id);

        }else {

            $msg_result = [
                $msg_title,
                "+{$subscribeObj->use_integral}分",
                $msg_time_day,
                $msg_class_time_string,
                $subscribeObj->class_name
            ];

            //扣减积分
            $remark = implode("/", $msg_result);

            UserSubscribeService::cancel_return_consumption($subscribeObj, $remark);
        }

        DB::commit();
    }

    public function change_subscribe_msg()
    {

    }

    public function check_change_subscribe($subscribe_id)
    {
        $SubscribeModel = new UserSubscribe();
        $Subscribe = $SubscribeModel->WhereID($subscribe_id)->select([
            'class_base_info_id',
            'class_time',
        ])
            ->with([
                'class_base_info' => function ($q) {
                    $q->select([
                        'id',
                        'advance_cancel_time',
                    ]);
                }
            ])
            ->first();
        // dd($Subscribe->class_time);
        date_default_timezone_set("PRC");

        $class_time = strtotime($Subscribe->class_time);
        //var_dump($class_time);die;
        $cancel_time = $class_time - $Subscribe->class_base_info->advance_cancel_time * 60;

        // dd(time(),$cancel_time,$Subscribe->class_base_info->advance_cancel_time);die;
        if (time() > $cancel_time) {
            return false;
        }
        return true;
    }

    public function refund_integral($use_integral, $user_id, $msg = '')
    {
        $total_integral = User::where('id', $user_id)->value('total_integral');
        $recordData['user_id'] = $user_id;
        $recordData['integral'] = $total_integral + $use_integral;
        $recordData['use_integral'] = $use_integral;
        $recordData['chage_type'] = 5;

        $recordData['reason'] = '退款積分-' . date("Y-m-d H:i:s") . '-' . $msg;
        $recordData['created_at'] = date("Y-m-d H:i:s");

        $res = User::where('id', $user_id)->increment('total_integral', $use_integral);
        $res2 = UserIntegralChangeRecord::insert($recordData);
        if ($res == true && $res2 == true) {
            return true;
        }
        return false;
    }
}
